package cn.com.yinhex.util;

import java.util.Random;

import net.rubyeye.xmemcached.XMemcachedClient;

public class RandomUtil {
	public static String STRING_VALUE = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
	
	public static String getRandStr(int length) {
		char[] value = STRING_VALUE.toCharArray();
		Random rand = new Random(System.currentTimeMillis());
		String result = "";
		for (int i = 0; i < length; i++) {
			int tmp = (int) (rand.nextFloat() * (value.length - 1));
			result += value[tmp];
		}
		return result;
	}

	public static void setRandom(String passport, String rand) {
		try {
		  getMemcachedClient().set(passport, 600, rand.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static boolean checkRandom(String passport, String rand) {
		String randC = null;
		try {
			randC = getMemcachedClient().get(passport);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (randC != null && randC.toLowerCase().equals(rand.toLowerCase())) {
		  removeRandom(passport);
		  return true;
		}
		return false;
	}
	
	public static void removeRandom(String passport){
		try {
		  getMemcachedClient().deleteWithNoReply(passport);
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}
	
/////////////////	
	public static void setRandomIp(String ip, String rand) {
    try {
      getMemcachedClient().set(ip, 600, rand.toString());
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public static boolean checkRandomIp(String ip, String rand) {
    String randC = null;
    try {
      randC = getMemcachedClient().get(ip);
    } catch (Exception e) {
      e.printStackTrace();
    }
    if (randC != null && randC.toLowerCase().equals(rand.toLowerCase())) {
      removeRandomIp(ip);
      return true;
    }
    return false;
  }
  
  public static void removeRandomIp(String ip){
    try {
      getMemcachedClient().deleteWithNoReply(ip);
    } catch (Exception e) {
      e.printStackTrace();
    } 
  }
	
	public static XMemcachedClient getMemcachedClient(){
		return (XMemcachedClient)SpringContextUtil.getBean("memcachedClient");
	}
}
